<template>
	<div>
		<van-nav-bar title="用户信息" />

		<div style="padding: 3vw;">

			<van-space direction="vertical" fill>
				<van-form label="个人用户信息">
					<van-field v-model="postForm.userName" label="用户名" />
					<van-field v-model="postForm.studentID" type="digit" label="学号"/>
					<van-field v-model="postForm.gender" label="性别" />
					<van-field v-model="password" type="password" label="新密码" />
					<van-field name="uploader" label="修改头像">
						<template #input>
							<van-uploader v-model="headImgs" :max-count="1"/>
						</template>
					</van-field>

				</van-form>
				<van-button @click="submitUpdateInfo" icon="back-top" type="success" round block>修改信息</van-button>
				<van-button @click="logoutButtonHandler" icon="cross" type="danger" round block>退出登录</van-button>
			</van-space>
		</div>
	</div>
</template>

<script>
	import {
		showNotify
	} from 'vant';
	import url from '@/assets/url.json';
	
	export default {
		props: {
			logoutAndLogin:Function,
			userData: Object,
			logoutEvent : Function,
			close : Function
		},

		data() {
			return {
				postForm: {
					userName: this.userData.userName + '',
					id: this.userData.id,
					studentID: this.userData.studentID === null ? '' : this.userData.studentID,
					gender: this.userData.gender
				},
				headImgs: [],
				password: ''
			}
		},
		
		methods:{
			submitUpdateInfo(){
				let formData = new FormData();
				if(this.headImgs.length>=1){
					formData.append('headImg',this.headImgs[0].file);
				}
				if(this.password!==''){
					formData.append('password',this.password);
				}
				
				for (let key in this.postForm) {
					formData.append(key,this.postForm[key]);
				}
				this.$axios({
					url:url.ip+'/api-user'+'/user/updateUser',
					method:'POST',
					data:formData,
					headers:{
						token: this.$cookies.get('token'),
						'Content-Type': 'multipart/form-data',
					}
				}).then((res)=>{
					if(res.data.code!==0){
						console.log(res);
						showNotify({ type: 'danger', message: res.data.message });
					}else{
						showNotify({ type: 'success', message: '修改信息成功' });
						this.close();
					}
				}).catch((err)=>{
					showNotify({ type: 'danger', message: err });
				})
				
			},
			logoutButtonHandler(){
				this.logout();
				this.logoutAndLogin();
			},
			logout(){
				this.$axios({
					url:url.ip+'/api-user'+'/user/logout',
					method:'GET',
					headers:{
						token: this.$cookies.get('token'),
					}
				}).then((res)=>{
					if(res.data.code!==0){
						console.log(res);
						showNotify({ type: 'danger', message: res.data.message });
					}else{
						showNotify({ type: 'success', message: '退出登录成功' });
						this.close();
					}
				}).catch((err)=>{
					showNotify({ type: 'danger', message: err });
				})
			}
		}
	}
</script>

<style>
</style>